import React, { memo, useState, useRef } from 'react';
import _ from 'lodash';
import { history } from 'umi';
import { Button, message, Popconfirm } from 'antd';
import CommonTable from '@/components/CommonTable';
import DebounceWrapper from '@/components/DebounceWrapper';
import DictDialog from './components/dictDialog';
import DictItemDialog from './components/dictItemDialog';
import { EyeOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { fetchDictList, deleteDictById } from '@/services/system/dictionary';

const DebounceButton = DebounceWrapper(Button);

export default memo(() => {
  const tableRef = useRef(null);
  const [deleteLoadingIds, setDeleteLoadingIds] = useState([]);
  const [dictModalOptions, setDictModalOptions] = useState({});
  const [dictModalVisible, setDictModalVisible] = useState(false);
  const [dictItemModalOptions, setDictItemModalOptions] = useState({});
  const [dictItemModalVisible, setDictItemModalVisible] = useState(false);

  // 切换loading
  const toggleDeleteLoading = (id, status) => {
    setDeleteLoadingIds((list) => {
      const nextList = [...list];
      if (status) {
        nextList.push(id);
      } else {
        const index = _.indexOf(nextList, id);
        if (index > -1) {
          nextList.splice(index, 1);
        }
      }
      return nextList;
    });
  };

  return (
    <>
      <CommonTable
        ref={tableRef}
        rowKey={'id'}
        indexRender
        header={{
          headerTitle: '字典列表',
          headerToolsRender: true,
          headerButtonList: [
            {
              key: 'add',
              type: 'primary',
              label: '新增',
              icon: <PlusOutlined />,
            },
          ],
          headerButtonClick: async ({ key }) => {
            switch (key) {
              case 'add':
                setDictModalVisible(true);
                break;
            }
          },
        }}
        request={async (params) => {
          const { records, total } = await fetchDictList(params);
          return { data: records, count: total };
        }}
        columns={[
          {
            title: '字典名称',
            dataIndex: 'dictName',
            columnControl: { typeList: 'search' },
          },
          { title: '字典编码', dataIndex: 'dictType', columnControl: { typeList: 'search' } },
          {
            title: '字典类型',
            dataIndex: 'dictProperty',
            columnControl: { typeList: 'filter', filterDictType: 'dict_property' },
          },
          {
            title: '字典状态',
            dataIndex: 'dictStatus',
            columnControl: { typeList: 'filter', filterDictType: 'dict_status' },
          },
          {
            title: '操作',
            dataIndex: 'id',
            width: 280,
            render: (text, data) => {
              const { dictName, dictType, dictProperty } = data;
              const deleteLoading = _.includes(deleteLoadingIds, text);
              return (
                <>
                  <DebounceButton
                    type="link"
                    size="small"
                    icon={<EyeOutlined />}
                    disabled={deleteLoading}
                    onClick={() => {
                      history.push({
                        pathname: 'detail',
                        state: { dictName, dictType, dictProperty },
                      });
                    }}
                  >
                    查看
                  </DebounceButton>
                  <DebounceButton
                    type="link"
                    size="small"
                    icon={<PlusOutlined />}
                    disabled={deleteLoading || dictProperty !== '1'}
                    onClick={() => {
                      setDictItemModalOptions({ dictType, dictName });
                      setDictItemModalVisible(true);
                    }}
                  >
                    新增
                  </DebounceButton>
                  <DebounceButton
                    type="link"
                    size="small"
                    icon={<EditOutlined />}
                    disabled={deleteLoading || dictProperty !== '1'}
                    onClick={() => {
                      setDictModalOptions(data);
                      setDictModalVisible(true);
                    }}
                  >
                    编辑
                  </DebounceButton>
                  <Popconfirm
                    okText="确定"
                    cancelText="取消"
                    title={'确认删除该字典数据，删除后不可恢复'}
                    placement="topRight"
                    disabled={dictProperty !== '1'}
                    onConfirm={async () => {
                      toggleDeleteLoading(text, true);
                      try {
                        await deleteDictById({ id: text });
                        const { refresh } = tableRef.current;
                        refresh && refresh();
                        message.success('字典数据删除成功');
                      } catch (e) {
                        console.log('删除失败');
                      }
                      toggleDeleteLoading(text, false);
                    }}
                  >
                    <DebounceButton
                      danger
                      type="link"
                      size="small"
                      icon={<DeleteOutlined />}
                      loading={deleteLoading}
                      disabled={dictProperty !== '1'}
                    >
                      删除
                    </DebounceButton>
                  </Popconfirm>
                </>
              );
            },
          },
        ]}
      />
      <DictDialog
        visible={dictModalVisible}
        options={dictModalOptions}
        closeModal={() => {
          setDictModalOptions({});
          setDictModalVisible(false);
        }}
        updateList={() => {
          const { refresh } = tableRef.current;
          refresh && refresh();
        }}
      />
      <DictItemDialog
        visible={dictItemModalVisible}
        options={dictItemModalOptions}
        closeModal={() => {
          setDictItemModalOptions({});
          setDictItemModalVisible(false);
        }}
      />
    </>
  );
});
